<?php
/*
 *---------------------------------------------------------------
 *  酷猴工作室 官方网址:http://kuhou.net
 *  淘宝店铺:https://shop137493962.taobao.com/
 *---------------------------------------------------------------
 *  author:  baoshu
 *  website: kuhou.net
 *  email:   83507315@qq.com
 */

namespace Addons\pinche\Controller;

use Mp\Controller\MobileBaseController;

/**
 * 拼车移动端控制器
 * @author 宝树
 */
class MobileController extends MobileBaseController
{
    public function _initialize() {
        // session(null);
        parent::_initialize();
        $fans_wechat_info = get_fans_wechat_info();
        // get_openid("o1nqxs9MuePOHWEY5jOgWfpVtlwU");
        // get_openid('oC6-GuHcCH8wA4jZQgt_LobtVVxc');         //别人
        // get_openid('o17d70z6j6yOFP2Su26R-5lWKDL8');      //我自己
    }
    /*
     * 首页
     */
    public function index($type = 2, $go = '')
    {

        $type = 2;      //设置只能获取车找货的用户
        // get_openid('GuMw6mRMu5tWfjI9CWy0Qu3M');
        $go = $_GET['go'];

        if (empty($go)) {
            $this->assign('go1', 'sel');
            $this->assign('go', 0);
        } elseif ($go == 2) {
            $this->assign('go2', 'sel');
            $this->assign('go', 2);
        }

        if ($type == 2) {
            $this->assign('type', 2);
            $this->assign('man', 'sel');
        } 

        if (isset($_GET['ffrom'])) {
            $this->assign('ffrom', $_GET['ffrom']);
        }
        if (isset($_GET['tto'])) {
            $this->assign('tto', $_GET['tto']);
        }

        $jssdk_sign = get_jssdk_sign_package();
        $this->assign('config', $jssdk_sign);

        $addon_config = get_addon_settings();
        $this->assign('addon_config', $addon_config);

        $system_settings = D('Admin/SystemSetting')->get_settings();
        $this->assign('meta_title', '');
        $this->assign('system_settings', $system_settings);
        $this->display();
    }

    /*
     * 发布拼车信息
     */
    public function add()
    {

        $config = get_addon_settings('pinche', get_mpid());
        // 查询是否验证手机号
        if (!$this->check_user_is_vail()) {
            redirect(create_addon_url('check_phone'));
        }

        //查询是否认证 车主认证
        $openid = get_openid();

        $_SESSION['user']['openid'] = $openid;

        $mpid = get_mpid();
        $bs_pinche_car_cert = D('bs_pinche_car_cert');

        $attention = $config['attention'];

        // 如果后台设置 发布必须关注本公众号
        if ($attention == 1) {
            $openid = get_openid();
            $fans_info = get_fans_info($openid);

            if ($fans_info['is_subscribe'] != 1) {
                $url = create_addon_url('attention');
                header("location: {$url}");
            }
        }

        // 查询是否收费
        if (!empty($config['charge']) && is_numeric($config['charge'])) {
            $charge = $config['charge'];
            if ($charge != 0) {
                $this->assign('add_money', $config['charge']);
            }
            $charge_tip = $config['charge_tip'];
            if (isset($charge_tip)) {
                $this->assign('charge_tip', $config['charge_tip']);
            }
        }

        // 获取默认 验证的手机号
        $info = array();
        $bs_pinche_sms = D('bs_pinche_sms');
        $openid = get_openid();
        $mpid = get_mpid();
//         $bs_pinche_sms_info = $bs_pinche_sms->where("openid = '{$openid}' AND mpid = {$mpid}")->order("id desc")->find();
//         if (isset($bs_pinche_sms_info['mobile'])) {
//             $info['tel'] = $bs_pinche_sms_info['mobile'];
// //            $this->assign('user_mobile',$bs_pinche_sms_info['mobile']);
//         }
        $info['tel'] = session('tel');
        $user_car_cert_info = D('bs_pinche_car_cert')->where("openid = '{$openid}' AND mpid = {$mpid}")->find();
        if (isset($user_car_cert_info['nickname'])) {
            $user_name = $user_car_cert_info['nickname'];
        }

        if (!empty($user_name)) {
            $info['contact'] = $user_name;
        }
        $this->assign('info', $info);

        $this->display();
    }

    /*
     * ajax 保存发布的
     */
    public function save($id = null)
    {
        $mpid = get_mpid();
        $pinche = D('bs_pinche');
        $openid = get_openid();
        if (empty($openid)) {
            $openid = $_SESSION['user']['openid'];
        }
        $mpid = get_mpid();
        $mp_fans = D('mp_fans');
        $userinfo = get_fans_info();

        $config = get_addon_settings('pinche', get_mpid());

        //查询是否认证 用户认证 车主认证

        $openid = get_openid();
        $bs_pinche_car_cert = D('bs_pinche_car_cert');
        $car_cert = $bs_pinche_car_cert->where("openid = '{$openid}' AND status = 1 AND mpid = {$mpid}")->find();

        // 车主认证后才允许发布
        $config = get_addon_settings('pinche', get_mpid());
        if ($config['car_is_cert_addinform'] == 1) {
            if ($_POST['Type'] == 1) {
                if (empty($car_cert)) {
                    //提示必须先认证车主
                    $json['code'] = 9;
                    $json['status'] = true;
                    $json['data'] = create_addon_url('car_cert');
                    $json['error'] = '必须先认证车主身份才能发布';
                    $this->ajaxReturn($json);
                    exit();
                }
            }

        }

        // 查询是否收费
        if (!empty($config['charge']) && is_numeric($config['charge'])) {
            $charge = $config['charge'];
            if ($charge != 0) {
                // 用户余额是否大于 发布费用
                if ($userinfo['money'] / 100 < $charge) {
                    $json['code'] = 8;
                    $json['status'] = true;
                    $json['data'] = create_addon_url('recharge');
                    $json['error'] = '您的余额不足,请先充值';
//                    . $userinfo['money'] . '-' . $charge
                    $this->ajaxReturn($json);
                    exit();
                }
            }
        }

        // 如果后台开启 用户每日最多发布数量
        $user_add_num = $config['user_add_num'] + 0;
        if (!empty($user_add_num) && is_numeric($user_add_num)) {
//            查询 改用户今日发布了多少条
            $now_date = strtotime(date("y-m-d", strtotime('now')));
            $user_pinche_count = $pinche->where("openid = '{$openid}' and pubtime > {$now_date} and mpid = {$mpid}")->count();
            if ($user_pinche_count >= $user_add_num) {
                $json['code'] = 7;
                $json['status'] = false;
                $json['data'] = '#';
                $json['error'] = '您今日发布超过最大限制 ' . $user_add_num . '条/天';
                $this->ajaxReturn($json);
                exit();
            }
        }

        if (IS_POST) {
            $data['mpid'] = get_mpid();
            $data['openid'] = get_openid();;
            $data['nickname'] = $userinfo['nickname'];
            $data['pubtime'] = time();
            $data['status'] = 0;
            $data['types'] = 2;//1 2   只允许添加车找货的
            $data['gotime'] = strtotime($_POST['DepTime']);

            if (strtotime($_POST['DepTime']) < time()) {
                $data['gotime'] = time() + (10 * 60);
            }

            // 出发地
            $data['from'] = $_POST['From'];
            $data['to'] = $_POST['To'];
            $data['money'] = $_POST['Money'];
            $data['num'] = $_POST['SeatCount'];
            $data['cartype'] = $_POST['CarType'];
            $data['through'] = $_POST['Through'];
            $data['people_count'] = $_POST['PeopleCount'];
            $data['remark'] = $_POST['Remark'];
            $data['contact'] = $_POST['Contact'];
            $data['tel'] = $_POST['Tel'];

//            update
            if (isset($id)) {
                $where['id'] = $id + 0;
                $where['mpid'] = get_mpid();
                $where['openid'] = get_openid();
                if ($pinche->data($data)->where($where)->save()) {
                    $userData = M('BsGuanzhu')->where(array('mpid'=>get_mpid(),'did'=>$id,'type'=>'pin','status'=>1))->getField('openid',true);
                    $url = create_mobile_url('detail',array('id'=>$id));
                    $temp_id = $config['update_temp'];
                    $arr = array(
                        "template_id"=>$temp_id,
                        "url"=>$url,
                        "topcolor"=>"#FF0000",
                        "data"=>array(
                          'first'=>array(
                            'value'=>'你关注的行程信息  从'.$data['from'].' 到 '.$data['to'].'的行程有新的消息，请点击查看',
                            "color"=>"#173177"
                          ),
                          'keyword1'=>array(
                            'value'=>date('Y-m-d H:i:s',time()),
                            "color"=>"#173177"
                          ),
                          'keyword2'=>array(
                            'value'=>'信息变更提醒',
                            "color"=>"#173177"
                          ),
                          'keyword3'=>array(
                            'value'=>$config['title'],
                            "color"=>"#173177"
                          ),
                          'keyword4'=>array(
                            'value'=>$config['title'],
                            "color"=>"#173177"
                          ),
                          'keyword5'=>array(
                            'value'=>'在线评车',
                            "color"=>"#173177"
                          ),
                          'remark'=>array(
                            'value'=>'如有疑问请致电',
                            "color"=>"#173177"
                          ),
                        )
                    );
                    $this->sendTemp($userData,$arr);                 //群发模板



                    $json['status'] = true;
                    $json['data'] = create_addon_url('detail') . '/id/' . $id;
                    $json['error'] = '';
                    $this->ajaxReturn($json);
                }
                exit();
            }


            //  置顶收费
            if ($_POST['TopIndex'] >= 1) {
                if (is_numeric($_POST['TopIndex'])) {
                    $config_key = 'charge' . $_POST['TopIndex'];
                    $charge_top = $config["$config_key"];
                    $charge_top_arr = explode('#', $charge_top);

                    $charge_time = $charge_top_arr[0];
                    $charge_money = $charge_top_arr[1];

                    // 查询是否收费
                    if (!empty($config['charge']) && is_numeric($config['charge'])) {
                        $charge = $config['charge'];

                        if ($userinfo['money'] / 100 < $charge_money + $charge) {
                            $json['code'] = 8;
                            $json['status'] = true;
                            $json['data'] = create_addon_url('recharge');
                            $json['error'] = '您的余额不足,请先充值';
                            $this->ajaxReturn($json);
                            exit();
                        } else {
                            // 扣费
                            $mp_fans->where("openid = '{$openid}' and mpid = {$mpid}")->setDec('money', $charge_money * 100);
//                        置顶天数
                            $data['top_time'] = time() + ($charge_time * 24 * 60 * 60);
                        }

                    } else {
                        if ($userinfo['money'] / 100 < $charge_money) {
                            $json['code'] = 8;
                            $json['status'] = true;
                            $json['data'] = create_addon_url('recharge');
                            $json['error'] = '您的余额不足,请先充值';
                            $this->ajaxReturn($json);
                            exit();
                        } else {
                            // 扣费
                            $mp_fans->where("openid = '{$openid}' and mpid = {$mpid}")->setDec('money', $charge_money * 100);
//                        置顶天数
                            $data['top_time'] = time() + ($charge_time * 24 * 60 * 60);
                        }
                    }

                }
            }

//            写入数据库
            if ($add_id = $pinche->data($data)->add()) {

                // 查询是否收费
                if (!empty($config['charge']) && is_numeric($config['charge'])) {
                    $charge = $config['charge'];
                    if ($charge != 0) {
                        // 扣费
                        $mpid = get_mpid();
                        $mp_fans->where("openid = '{$openid}' and mpid = {$mpid}")->setDec('money', $charge * 100);
                    }
                }
                /*设置session*/
                session('tel',I('post.tel'));
                                    // $car_user = "o1nqxs8hrplDUwjvz_uqK258T9s4";
                    // $findCarMap = "mpid=".get_mpid()." AND cartype={$data['cartype']} AND types = 1 AND (`from` like '%{$data['from']}%' OR `to` like '%{$data['to']}%' OR `through` like '%{$data['from']}%' OR `through` like '%{$data['to']}%')";
                    $findCarMap['mpid'] = get_mpid();
                    $findCarMap['types'] = 1;
                    $car_user = M('BsPinche')->where($findCarMap)->getField('openid',true);
                    $car_user = array_unique($car_user);
                    $userData = $car_user;
                    $arr = array(
                    "template_id"=>"cUsROlxvBuZFFl8msrSHnuUopN0d9EAtHutDmdaaTKw",
                    "url"=>create_mobile_url('detail',array('id'=>$add_id)),
                    "topcolor"=>"#FF0000",
                    "data"=>array(
                        'first'=>array(
                            'value'=>"你好，有物流需要你运送！!",
                            "color"=>"#DC143C"
                        ),
                        'keyword1'=>array(
                            'value'=>"从".$data['from']."到".$data['to'],
                            "color"=>"#173177"
                        ),
                        'keyword2'=>array(
                            'value'=>"数量：".$_POST['SeatCount'].',车型：'.($data['cartype'] ==1?'保温':'冷藏'),
                            "color"=>"#173177"
                        ),
                        'remark'=>array(
                            'value'=>"交易过程的问题，请致电客服 01057488855",
                            "color"=>"#173177"
                        ),
                    )
                );
                   $this->sendTemp($userData,$arr);



//                写入成功
                $json['status'] = true;
                $json['data'] = create_addon_url('detail') . '/id/' . $add_id;
                $json['error'] = '';
                $this->ajaxReturn($json);
                exit();
            } else {
//                写入失败
                $json['status'] = false;
                $json['data'] = '#';
                $json['error'] = '发布失败';
                $this->ajaxReturn($json);
                exit();
            }
        }
    }

    /*
     * ajax 列表
     */

/*
    public function lists()
    {
        $page = $_GET['page'];
        $start = ($page - 1) * 8;
        $num = 8;
        $pinche = D('bs_pinche');

        //根据拼车类型查询
        $type = $_GET['type'];
        if (isset($type)) {
            $where['types'] = $type;
        }

        //根据时间查询 显示不过期的
        $go = $_GET['go'];
        if ($go == 2) {
            $where['gotime'] = array('EGT', time());
        }

        //搜索
        if (isset($_GET['ffrom'])) {
            $where["from"] = array("like", "%" . $_GET['ffrom'] . "%");
        }
        if (isset($_GET['tto'])) {
            $where["to"] = array("like", "%" . $_GET['tto'] . "%");
        }

        $where['mpid'] = get_mpid();

        $where['is_top'] = 0;

        // user top
//        $where2 = array();
        $where2 = $where;
        $where2['is_top'] = 1;
        $pinche_lists2 = $pinche->where($where2)->order('pubtime desc')->limit($start, $num)->select();
        foreach ($pinche_lists2 as $k2 => $v2) {
            $pinche_lists2[$k2]['is_top'] = 1;
            $pinche_lists2[$k2]['gotime'] = time() + 100;
        }

        // user pay top
        $where3 = array();
        $where3 = $where;
        $where3['top_time'] = array('GT', time());
        $pinche_lists3 = $pinche->where($where3)->order('pubtime desc')->limit($start, $num)->select();
        foreach ($pinche_lists3 as $k3 => $v3) {
            $pinche_lists3[$k3]['is_top'] = 1;
            $pinche_lists3[$k3]['gotime'] = time() + 100;
        }

        $config = get_addon_settings('pinche', get_mpid());
        $timeout = $config['timeout'];

        // timeout no show
        if ($timeout == 2) {
            $where['gotime'] = array('egt', time());
        }

        $pinche_lists = $pinche->where($where)->order('pubtime desc')->limit($start, $num)->select();

        if (!empty($pinche_lists2)) {
            $pinche_lists = array_merge($pinche_lists2, $pinche_lists);
        }

        if (!empty($pinche_lists3)) {
            $pinche_lists = array_merge($pinche_lists3, $pinche_lists);
        }

        $arr = array();
        foreach ($pinche_lists as $key => $value) {
//            is top?
            $arr[$key]['Remark'] = $pinche_lists[$key]['remark'];
            $arr[$key]['Url'] = __APP__ . '/addon/pinche/mobile/detail/id/' . $pinche_lists[$key]['id'] . '/mpid/' . get_mpid();

            $arr[$key]['Id'] = $pinche_lists[$key]['id'];

            $openid = $pinche_lists[$key]['openid'];
            $mp_fans = D('mp_fans');
            $userinfo = $mp_fans->where("openid = '{$openid}'")->find();
            if ($userinfo) {
                $arr[$key]['UserFace'] = $userinfo['headimgurl'];
                $arr[$key]['Sex'] = $userinfo['sex'];
            } else {
                $arr[$key]['UserFace'] = "";
                $arr[$key]['Sex'] = 1;
            }

            $arr[$key]['From'] = $pinche_lists[$key]['from'];
            $arr[$key]['To'] = $pinche_lists[$key]['to'];
            $arr[$key]['Tel'] = $pinche_lists[$key]['tel'];
            $arr[$key]['Contact'] = $pinche_lists[$key]['contact'];
            $arr[$key]['NickName'] = mb_substr($pinche_lists[$key]['nickname'], 0, 15, "UTF-8");
            $arr[$key]['SeatCount'] = $pinche_lists[$key]['num'];
            $arr[$key]['PeopleCount'] = $pinche_lists[$key]['people_count'];
            $arr[$key]['Through'] = $pinche_lists[$key]['through'];
            $arr[$key]['DepTime'] = date('Y-m-d H:i:s', $pinche_lists[$key]['gotime']);
            $arr[$key]['Type'] = $pinche_lists[$key]['types'];
            $arr[$key]['Money'] = ceil($pinche_lists[$key]['money']);
            $arr[$key]['TopIndex'] = $pinche_lists[$key]['is_top'];
            // $arr[$key]['CarType'] = $pinche_lists[$key]['cartype'];

            $car_type = $pinche_lists[$key]['cartype'];

            switch ($car_type) {
                case 0:
                    $car_types = '';
                    break;
                case 1:
                    $car_types = '小轿车';
                    break;
                case 2:
                    $car_types = 'SUV';
                    break;
                case 3:
                    $car_types = '微面';
                    break;
                case 4:
                    $car_types = '货车';
                    break;
                default:
                    $car_types = '';
                    break;
            }

            $arr[$key]['CarType'] = $car_types;


//            time is end?
            if ($pinche_lists[$key]['gotime'] > time()) {
                $arr[$key]['IsOverdue'] = false;
            } else {
                $arr[$key]['IsOverdue'] = ture;
            }
        }

        $data['status'] = true;
        $data['data'] = $arr;

        $this->ajaxReturn($data);
    }
*/
/*
     * ajax 列表
     */
    public function lists()
    {
        $page = $_GET['page'];
        $start = ($page - 1) * 8;
        $num = 8;
        $pinche = D('bs_pinche');

        //根据拼车类型查询
        $type = $_GET['type'];
        if (isset($type)) {
            $where['types'] = $type;
        }

        //根据时间查询 显示不过期的
        $go = $_GET['go'];
        if ($go == 2) {
            $where['gotime'] = array('EGT', time());
        }

        //搜索
        $mpid = get_mpid();
        $pinche_ser = '';
//        if(isset($_GET['ffrom'])||isset($_GET['tto']){
        if (isset($_GET['ffrom'])) {
//            $where["from"] = array("like", "%" . $_GET['ffrom'] . "%");
            $sql = "select * from dc_bs_pinche where mpid = {$mpid} AND `from` like '%" . $_GET['ffrom'] . "%' OR `to` like '%" . $_GET['ffrom'] . "%' OR through like '%" . $_GET['ffrom'] . "%' limit {$start},{$num}";
            $pinche_ser = $pinche->query($sql);


            $pinche_lists = $pinche_ser;

            $arr = array();
            foreach ($pinche_lists as $key => $value) {
//            is top?
                $arr[$key]['Remark'] = $pinche_lists[$key]['remark'];
                $arr[$key]['Url'] = __APP__ . '/addon/pinche/mobile/detail/id/' . $pinche_lists[$key]['id'] . '/mpid/' . get_mpid();

                $arr[$key]['Id'] = $pinche_lists[$key]['id'];

                $openid = $pinche_lists[$key]['openid'];
                $mp_fans = D('mp_fans');
                $userinfo = $mp_fans->where("openid = '{$openid}'")->find();
                if ($userinfo) {
                    $arr[$key]['UserFace'] = $userinfo['headimgurl'];
                    $arr[$key]['Sex'] = $userinfo['sex'];
                } else {
                    $arr[$key]['UserFace'] = "";
                    $arr[$key]['Sex'] = 1;
                }

                $arr[$key]['From'] = $pinche_lists[$key]['from'];
                $arr[$key]['To'] = $pinche_lists[$key]['to'];
                $arr[$key]['Tel'] = $pinche_lists[$key]['tel'];
                $arr[$key]['Contact'] = $pinche_lists[$key]['contact'];
                $arr[$key]['NickName'] = mb_substr($pinche_lists[$key]['nickname'], 0, 15, "UTF-8");
                $arr[$key]['SeatCount'] = $pinche_lists[$key]['num'];
                $arr[$key]['PeopleCount'] = $pinche_lists[$key]['people_count'];
                $arr[$key]['Through'] = $pinche_lists[$key]['through'];
                $arr[$key]['DepTime'] = date('Y-m-d H:i:s', $pinche_lists[$key]['gotime']);
                $arr[$key]['Type'] = $pinche_lists[$key]['types'];
                $arr[$key]['Money'] = ceil($pinche_lists[$key]['money']);
                $arr[$key]['TopIndex'] = $pinche_lists[$key]['is_top'];
                // $arr[$key]['CarType'] = $pinche_lists[$key]['cartype'];

                $car_type = $pinche_lists[$key]['cartype'];

                switch ($car_type) {
                    case 0:
                        $car_types = '';
                        break;
                    case 1:
                        $car_types = '小轿车';
                        break;
                    case 2:
                        $car_types = '冷藏车';
                        break;
                    case 3:
                        $car_types = '微面';
                        break;
                    case 4:
                        $car_types = '货车';
                        break;
                    default:
                        $car_types = '';
                        break;
                }

                $arr[$key]['CarType'] = $car_types;


//            time is end?
                if ($pinche_lists[$key]['gotime'] > time()) {
                    $arr[$key]['IsOverdue'] = false;
                } else {
                    $arr[$key]['IsOverdue'] = ture;
                }
            }

            $data['status'] = true;
            $data['data'] = $arr;
            $this->ajaxReturn($data);




        }
        if (isset($_GET['tto'])) {
//            $where["to"] = array("like", "%" . $_GET['tto'] . "%");
            $sql = "select * from dc_bs_pinche where mpid = {$mpid} AND `from` like '%" . $_GET['tto'] . "%' OR `to` like '%" . $_GET['tto'] . "%' OR through like '%" . $_GET['tto'] . "%' limit {$start},{$num}";


            $pinche_ser = $pinche->query($sql);

            $pinche_lists = $pinche_ser;

            $arr = array();
            foreach ($pinche_lists as $key => $value) {
//            is top?
                $arr[$key]['Remark'] = $pinche_lists[$key]['remark'];
                $arr[$key]['Url'] = __APP__ . '/addon/pinche/mobile/detail/id/' . $pinche_lists[$key]['id'] . '/mpid/' . get_mpid();

                $arr[$key]['Id'] = $pinche_lists[$key]['id'];

                $openid = $pinche_lists[$key]['openid'];
                $mp_fans = D('mp_fans');
                $userinfo = $mp_fans->where("openid = '{$openid}'")->find();
                if ($userinfo) {
                    $arr[$key]['UserFace'] = $userinfo['headimgurl'];
                    $arr[$key]['Sex'] = $userinfo['sex'];
                } else {
                    $arr[$key]['UserFace'] = "";
                    $arr[$key]['Sex'] = 1;
                }

                $arr[$key]['From'] = $pinche_lists[$key]['from'];
                $arr[$key]['To'] = $pinche_lists[$key]['to'];
                $arr[$key]['Tel'] = $pinche_lists[$key]['tel'];
                $arr[$key]['Contact'] = $pinche_lists[$key]['contact'];
                $arr[$key]['NickName'] = mb_substr($pinche_lists[$key]['nickname'], 0, 15, "UTF-8");
                $arr[$key]['SeatCount'] = $pinche_lists[$key]['num'];
                $arr[$key]['PeopleCount'] = $pinche_lists[$key]['people_count'];
                $arr[$key]['Through'] = $pinche_lists[$key]['through'];
                $arr[$key]['DepTime'] = date('Y-m-d H:i:s', $pinche_lists[$key]['gotime']);
                $arr[$key]['Type'] = $pinche_lists[$key]['types'];
                $arr[$key]['Money'] = ceil($pinche_lists[$key]['money']);
                $arr[$key]['TopIndex'] = $pinche_lists[$key]['is_top'];
                // $arr[$key]['CarType'] = $pinche_lists[$key]['cartype'];

                $car_type = $pinche_lists[$key]['cartype'];

                switch ($car_type) {
                    case 0:
                        $car_types = '';
                        break;
                    case 1:
                        $car_types = '保温车';
                        break;
                    case 2:
                        $car_types = '冷藏车';
                        break;
                    case 3:
                        $car_types = '微面';
                        break;
                    case 4:
                        $car_types = '货车';
                        break;
                    default:
                        $car_types = '';
                        break;
                }

                $arr[$key]['CarType'] = $car_types;


//            time is end?
                if ($pinche_lists[$key]['gotime'] > time()) {
                    $arr[$key]['IsOverdue'] = false;
                } else {
                    $arr[$key]['IsOverdue'] = ture;
                }
            }

            $data['status'] = true;
            $data['data'] = $arr;
            $this->ajaxReturn($data);

//            $where["from"] = array("like", "%" . $_GET['tto'] . "%");
//            $where['_logic'] = 'OR';
        }
//        }


        $where['mpid'] = get_mpid();

        $where['is_top'] = 0;

        // user top
//        $where2 = array();
        $where2 = $where;
        $where2['is_top'] = 1;

//        if (!empty($pinche_ser)) {
//            $pinche_lists2 = $pinche_ser;
//        } else {
            $pinche_lists2 = $pinche->where($where2)->order('pubtime desc')->limit($start, $num)->select();
//        }

        foreach ($pinche_lists2 as $k2 => $v2) {
            $pinche_lists2[$k2]['is_top'] = 1;
            $pinche_lists2[$k2]['gotime'] = time() + 100;
        }

        // user pay top
        $where3 = array();
        $where3 = $where;
        $where3['top_time'] = array('GT', time());
        $pinche_lists3 = $pinche->where($where3)->order('pubtime desc')->limit($start, $num)->select();
        foreach ($pinche_lists3 as $k3 => $v3) {
            $pinche_lists3[$k3]['is_top'] = 1;
            $pinche_lists3[$k3]['gotime'] = time() + 100;
        }

        $config = get_addon_settings('pinche', get_mpid());
        $timeout = $config['timeout'];

        // timeout no show
        if ($timeout == 2) {
            $where['gotime'] = array('egt', time());
        }

        $pinche_lists = $pinche->where($where)->order('pubtime desc')->limit($start, $num)->select();

        if (!empty($pinche_lists2)) {
            $pinche_lists = array_merge($pinche_lists2, $pinche_lists);
        }

        if (!empty($pinche_lists3)) {
            $pinche_lists = array_merge($pinche_lists3, $pinche_lists);
        }

        $arr = array();
        foreach ($pinche_lists as $key => $value) {
//            is top?
            $arr[$key]['Remark'] = $pinche_lists[$key]['remark'];
            $arr[$key]['Url'] = __APP__ . '/addon/pinche/mobile/detail/id/' . $pinche_lists[$key]['id'] . '/mpid/' . get_mpid();

            $arr[$key]['Id'] = $pinche_lists[$key]['id'];

            $openid = $pinche_lists[$key]['openid'];
            $mp_fans = D('mp_fans');
            $userinfo = $mp_fans->where("openid = '{$openid}'")->find();
            if ($userinfo) {
                $arr[$key]['UserFace'] = $userinfo['headimgurl'];
                $arr[$key]['Sex'] = $userinfo['sex'];
            } else {
                $arr[$key]['UserFace'] = "";
                $arr[$key]['Sex'] = 1;
            }

            $arr[$key]['From'] = $pinche_lists[$key]['from'];
            $arr[$key]['To'] = $pinche_lists[$key]['to'];
            $arr[$key]['Tel'] = $pinche_lists[$key]['tel'];
            $arr[$key]['Contact'] = $pinche_lists[$key]['contact'];
            $arr[$key]['NickName'] = mb_substr($pinche_lists[$key]['nickname'], 0, 15, "UTF-8");
            $arr[$key]['SeatCount'] = $pinche_lists[$key]['num'];
            $arr[$key]['PeopleCount'] = $pinche_lists[$key]['people_count'];
            $arr[$key]['Through'] = $pinche_lists[$key]['through'];
            $arr[$key]['DepTime'] = date('Y-m-d H:i:s', $pinche_lists[$key]['gotime']);
            $arr[$key]['Type'] = $pinche_lists[$key]['types'];
            $arr[$key]['Money'] = ceil($pinche_lists[$key]['money']);
            $arr[$key]['TopIndex'] = $pinche_lists[$key]['is_top'];
            // $arr[$key]['CarType'] = $pinche_lists[$key]['cartype'];

            $car_type = $pinche_lists[$key]['cartype'];

            switch ($car_type) {
                case 0:
                    $car_types = '';
                    break;
                case 1:
                    $car_types = '保温车';
                    break;
                case 2:
                    $car_types = '冷藏车';
                    break;
                case 3:
                    $car_types = '微面';
                    break;
                case 4:
                    $car_types = '货车';
                    break;
                default:
                    $car_types = '';
                    break;
            }

            $arr[$key]['CarType'] = $car_types;


//            time is end?
            if ($pinche_lists[$key]['gotime'] > time()) {
                $arr[$key]['IsOverdue'] = false;
            } else {
                $arr[$key]['IsOverdue'] = ture;
            }
        }

        $data['status'] = true;
        $data['data'] = $arr;
        $this->ajaxReturn($data);


    }



    /*
     * 拼车详情
     */
    public function detail($id = null)
    {
        $user_openid = get_openid();
        $id = $id + 0;

        $pinche = D('bs_pinche');
        $info = $pinche->where("id = {$id}")->find();

        $openid = $info['openid'];
        $mp_fans = D('mp_fans');
        $userinfo = $mp_fans->where("openid = '{$openid}'")->find();
        if ($userinfo) {
            $info['UserFace'] = $userinfo['headimgurl'];
            $info['Sex'] = $userinfo['sex'];
        } else {
            $info['UserFace'] = "";
            $info['Sex'] = 1;
        }

        $car_type = $info['cartype'];

        switch ($car_type) {
            case 0:
                $car_types = '';
                break;
            case 1:
                $car_types = '保温车';
                break;
            case 2:
                $car_types = '冷藏车';
                break;
            case 3:
                $car_types = '微面';
                break;
            case 4:
                $car_types = '货车';
                break;
            default:
                $car_types = '';
                break;
        }
        $info['CarType'] = $car_types;

        $jssdk_sign = get_jssdk_sign_package();
        $this->assign('config', $jssdk_sign);

        $system_settings = D('Admin/SystemSetting')->get_settings();
        $this->assign('meta_title', '');
        $this->assign('system_settings', $system_settings);

        $addon_config = get_addon_settings();
        $this->assign('addon_config', $addon_config);

        $this->assign('info', $info);

        $this->assign('id', $id);

        $this->assign('user_openid', $user_openid);
        $this->display();
    }

    /*
     * 用户中心
     */
    public function user()
    {
        $this->assign('user', get_fans_info());
        $this->display();
    }

    /*
     * 用户发布的
     */
    public function user_push()
    {
        $userinfo = get_fans_info();
        $pinche = D('bs_pinche');

        $where['openid'] = $userinfo['openid'];
        $where['mpid'] = $userinfo['mpid'];
        $where['types'] = 2;

        $arr = $pinche->order('pubtime desc')->where($where)->select();
        $this->assign('info', $arr);
        $this->display();
    }

    /*
     * 更新发布的拼车信息
     */
    public function update($id = null)
    {
        $id = $id + 0;
        $pinche = D('bs_pinche');
        $where['id'] = $id;
        $where['mpid'] = get_mpid();
        $where['openid'] = get_openid();
        $info = $pinche->where($where)->find();

        $info['action'] = 'update';

        $this->assign('info', $info);
        $this->display('add');
    }

    /*
     * 删除发布的拼车信息
     */
    public function del($id = null)
    {
        $id = $id + 0;           
        $pinche = D('bs_pinche');
        $where['id'] = $id;
        $where['mpid'] = get_mpid();
        $where['openid'] = get_openid();

        if ($pinche->where($where)->delete()) {
            $data['status'] = true;
            $data['data'] = null;
            $data['error'] = '';
            $this->ajaxReturn($data);
        }
    }

    /*
     * 关注提示
     */
    public function attention()
    {
        $config = get_mp_info(get_mpid());
        $this->assign('config', $config);
        $this->display();
    }

    /*
     * 充值
     */
    public function recharge()
    {
        $settings = get_addon_settings();
        if ($settings['recharge']) {
            if (strpos($settings['recharge'], ',')) {
                $recharge = explode(',', $settings['recharge']);
            } else {
                $recharge = explode('，', $settings['recharge']);
            }
        }

        $this->assign('recharge', $recharge);

        $this->display();
    }

    /*
     * 充值ajax
     */
    public function recharge_ajax()
    {
        $data['mpid'] = get_mpid();
        $data['openid'] = get_openid();
        $data['money'] = floatval(I('price'));
        $data['pay_status'] = 0;
        $data['create_time'] = time();
        $data['is_show'] = 0;
        $data['is_ok'] = 0;
        $data['orderid'] = $data['mpid'] . time();

        $res = M('bs_pay_list')->add($data);

        if (!$res) {
            $data['errcode'] = 0;
            $data['errmsg'] = '支付失败';
        } else {
            $data['errcode'] = 1;
            $data['errmsg'] = '支付成功';
            $data['notify'] = create_addon_url('recharge_ok');
            $data['jump_url'] = create_addon_url('recharge_ok');
        }
        $this->ajaxReturn($data);
    }

    /**
     * 充值成功
     */
    public function recharge_ok()
    {
        /*
         * 微信服务器回调
         */
        if (I('result_code') == 'SUCCESS' && I('return_code') == 'SUCCESS') {
            $map['orderid'] = I('out_trade_no');
            $data['pay_status'] = 1;
            $data['is_show'] = 1;
            M('bs_pay_list')->where($map)->save($data);

            $bs_pay = M('bs_pay_list');
            $pay_list = $bs_pay->where($map)->find();

            $order_status = $pay_list['is_ok'];
            /*
             * 防止微信多次回调
             */
            if ($order_status == 0) {
                $ok['is_ok'] = 1;
                M('bs_pay_list')->where($map)->save($ok);

                $pay_money = $pay_list['money'] * 100;
                /*
                 * 给用户加余额
                 */
                $oid = $pay_list['openid'];
                $mp_fans = D('mp_fans');

                $mpid = $pay_list['mpid'];
                $mp_fans->where("openid = '{$oid}' and mpid = {$mpid}")->setInc('money', $pay_money);
            }

        } else {
//            如果来自用户访问 跳转用户中心
            $url = create_addon_url('user');
            header("location: $url");
        }
    }


    /*
     * 车主认证
     */
    public function car_cert()
    {
        if (!$this->check_user_is_vail()) {
            redirect(create_addon_url('check_phone'));
        }

        $openid = get_openid();
        $car_cert_db = D('bs_pinche_car_cert');
        $car_cert_info = $car_cert_db->where("openid = '{$openid}'")->find();
        if ($car_cert_info) {
            $this->assign('userinfo', $car_cert_info);
            $this->assign('state', $car_cert_info['status']);
        }

        $this->display();
    }

    /*
     * 保存车主认证信息
     */
    public function car_cert_ajax()
    {

        // 先查询数据库是否存在 status 0 代表审核中 1审核成功
        $openid = get_openid();
        $car_cert_db = D('bs_pinche_car_cert');
        $name = $_POST['name'];
        $imgs = $_POST['img'];

        // $img1 = strpos($imgs[0],'jpg') ? $imgs[0] : $this->uploadImg("7XzOyWz-Hb2Gz9bufpOcTtwXI1_hxgALB_PbgevAfnXjarKYfpBCUCXn7zUzs61U");
        // $img2 = strpos($imgs[1],'jpg') ? $imgs[1] : $this->uploadImg("7XzOyWz-Hb2Gz9bufpOcTtwXI1_hxgALB_PbgevAfnXjarKYfpBCUCXn7zUzs61U");
        // $img3 = strpos($imgs[2],'jpg') ? $imgs[2] : $this->uploadImg("U0I1IVUwOkIV98NLOHUBwXeLOyFnRtOHW2IkYnoXcUX7jOg-VT160IQJc2hJJaZj");
        // $img4 = strpos($imgs[3],'jpg') ? $imgs[3] : $this->uploadImg("oH_34mJI8K6XDZXxN4aDmOuUMdzID8ENnaYa6_m5S9cqNvOoZc5P5Q-dCCb4AdV5");
        // $img1 = $this->dlfile($imgs[0]);
        // $img2 = $this->dlfile($imgs[1]);
        // $img3 = $this->dlfile($imgs[2]);
        // $img4 = $this->dlfile($imgs[3]);
        
         $img1 = strpos($imgs[0],'jpg') ? $imgs[0] : $this->uploadImg($imgs[0]);
         $img2 = strpos($imgs[1],'jpg') ? $imgs[1] : $this->uploadImg($imgs[1]);
         $img3 = strpos($imgs[2],'jpg') ? $imgs[2] : $this->uploadImg($imgs[2]);
         $img4 = strpos($imgs[3],'jpg') ? $imgs[3] : $this->uploadImg($imgs[3]);
        if(!$img1 || !$img2 || !$img4 || !$img4){
            $json['result'] = 0;
            $json['msg'] = '上传失败，请重新上传';
            exit(json_encode($json));
        }
        $data = array(
            'mpid' => get_mpid(),
            'openid' => $openid,
            'nickname' => $name,
            'car_type' => $_POST['carType'],
            'car_num' => $_POST['carNum'],
            'id_card' => $img1,
            'car_img' => $img2,
            'card1' => $img3,
            'card2' => $img4,
            'addtime' => time(),
            'status' => 0
        );

        /*
         * 如果添加过
         */
        if (!empty($_POST['state'])) {
            $car_cert_db->where("openid = '{$openid}'")->save($data);
            $json['result'] = 2;
            $json['msg'] = '修改成功,等待审核';
            exit(json_encode($json));
        } else {

            /*
             * 查询状态 如果没有提交过 则添加
             */
            $car_cert_info = $car_cert_db->where("openid = '{$openid}'")->find();
            if ($car_cert_info) {
                if ($car_cert_info['status'] == 0) {
                    $json['result'] = 0;
                    $json['msg'] = '审核中';
                    exit(json_encode($json));
                } elseif ($car_cert_info['status'] == 1) {
                    $json['result'] = 1;
                    $json['msg'] = '审核通过';
                    exit(json_encode($json));
                }
            }

            if ($car_cert_db->add($data)) {
                $json['result'] = 2;
                $json['msg'] = '提交成功,等待审核';
                exit(json_encode($json));
            } else {
                $json['result'] = 3;
                $json['msg'] = '提交失败,请稍后再试';
                exit(json_encode($json));
            }

        }

    }
    /*下载微信服务器图片*/

    public function uploadImg($mediaId){

        $imgDir   = './Uploads/Pictures/OrderImg';

        if(!is_dir($imgDir)){

            mkdir($imgDir);

        }

        $imgPath  = $imgDir.'/'.$mediaId.'.jpg';

        $wechatObj = get_wechat_obj();
         $str = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$wechatObj->checkAuth()."&media_id=".$mediaId.""; 
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl,CURLOPT_TIMEOUT,500);
         curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
         curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
         curl_setopt($curl,CURLOPT_URL,$str);
         $res = curl_exec($curl);
         curl_close($curl);
         $x = json_decode($res);
         if($x['errcode']) $this->error('错误');
         file_put_contents($imgPath,$res);
         return $imgPath;

        // $str = file_get_contents($str);
        // $json = json_decode($str);
        // $gg = $json->base64;
        // $size = $json->size;
        // $ld = strlen($gg);
        // if ($size == $ld) {
        //     if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $gg, $result)) {
        //         $type = $result[2];
        //         $filename = date("YmdHis") . rand(100, 999);
        //         $new_file = "./Uploads/{$filename}.{$type}";
        //         $path = "{$filename}.{$type}";
        //         if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $gg)))) {
        //             return $path;
        //         }
        //     }
        // } else {
        //     $this->error('错误!');
        // }
    }

    function dlfile($mediaId)
    { 
        $imgDir   = './Uploads/Pictures/UploadImg';
        if(!is_dir($imgDir)){
            mkdir($imgDir);
        }
        $imgPath  = $imgDir.'/'.time().mt_rand(0,1000).'.jpg';
        $wechatObj = get_wechat_obj();
         $str = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$wechatObj->checkAuth()."&media_id=".$mediaId.""; 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 0); 
        curl_setopt($ch,CURLOPT_URL,$str); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        $file_content = curl_exec($ch);
        curl_close($ch);
        $downloaded_file = fopen($imgPath, 'w');
        fwrite($downloaded_file, $file_content);
        fclose($downloaded_file);
        return $imgPath;
    }


    /*
     * 上传图片
     */
    public function formdata()
    {
        $str = file_get_contents('php://input');
        $json = json_decode($str);
        $gg = $json->base64;
        $size = $json->size;
        $ld = strlen($gg);
        if ($size == $ld) {
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $gg, $result)) {
                $type = $result[2];
                $filename = date("YmdHis") . rand(100, 999);
                $new_file = "./Public/{$filename}.{$type}";
                $path = "{$filename}.{$type}";
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $gg)))) {
                    $dat['error'] = 0;
                    $dat['url'] = $path;
                    $_SESSION['img'] = $dat['url'];
                    $this->ajaxReturn($dat);
                }
            }
        } else {
            $dat['error'] = 1;
            echo json_encode($dat);
            return;
        }
    }

    private function check_user_is_vail()
    {
        $settings = get_addon_settings();
        if (empty($settings['is_open_check_sms'])) {
            return ture;
        }
        if ($settings['is_open_check_sms']) {
            if ($settings['is_open_check_sms'] == 2) {
                return ture;
            }
        }

        // 查询是否验证手机号
        $mobile_check_db = D('bs_pinche_mobile_check');
        $openid = get_openid();
        $mpid = get_mpid();
        $is_check_mobile = $mobile_check_db->where("openid = '{$openid}' AND mpid = {$mpid} AND status = 1")->find();
        if (!$is_check_mobile) {
            return false;
        } else {
            return ture;
        }
    }


    /*
     * 发布都需要认证，第一次查看、发布先验证手机号。
     */
    public function check_phone()
    {
        $this->display();
    }

    /*
     * 发送验证码
     */
    public function send_sms()
    {
        $_SESSION['tel'] = $_POST['tel'];
        $_SESSION['code'] = $this->_createSMSCode();

        $result = $this->_sendSMSCode($_SESSION['tel']);
        if ($result['code'] == 0) {
            $json['result'] = 1;
            $json['msg'] = '验证码';
        }elseif($result['code'] == 2){
            $json['result'] = 0;
            $json['msg'] = $result['msg'];
        } else {
            $json['result'] = 0;
            $json['msg'] = '';
            $json['attr'] = $result;
        }
        echo json_encode($json);
    }

    /*
     * 检验验证码是否正确
     */
    public function check_sms()
    {
        $code = $_POST['code'];
        //验证码正确
        if ($code == $_SESSION['code']) {
            // 验证成功
            $data = array(
                'mpid' => get_mpid(),
                'openid' => get_openid(),
                'mobile' => $_SESSION['tel'],
                'addtime' => time(),
                'status' => 1
            );
            $mobile_check_db = D('bs_pinche_mobile_check');
            $mobile_check_db->add($data);

            $json['result'] = 1;
            $json['msg'] = '';
            echo json_encode($json);
        } else {
            $json['result'] = 0;
            $json['msg'] = '验证码不正确';
            echo json_encode($json);
        }
    }

    // 生成短信验证码
    public function _createSMSCode($length = 4)
    {
        $min = pow(10, ($length - 1));
        $max = pow(10, $length) - 1;
        return rand($min, $max);
    }

    // 获取短信验证码
    public function _sendSMSCode($mobile)
    {
        $code = $_SESSION['code'];

        $config = get_addon_settings('pinche', get_mpid());

        $ch = curl_init();
        $url = 'https://sms.yunpian.com/v1/sms/send.json';
        curl_setopt($ch, CURLOPT_URL, $url);

        $paramArr = array(
            'apikey' => $config['yunpian_apikey'],
            'mobile' => $mobile,
            'text' => '您的验证码是' . $code . '。如非本人操作，请忽略本短信'
        );
        $param = '';
        foreach ($paramArr as $key => $value) {
            $param .= urlencode($key) . '=' . urlencode($value) . '&';
        }
        $param = substr($param, 0, strlen($param) - 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $outputArr = json_decode($output, true);

        $data['mpid'] = get_mpid();
        $data['openid'] = get_openid();
        $data['mobile'] = $mobile;
        $data['code'] = $code;
        $data['sendtime'] = time();

        $smscode = D('bs_pinche_sms');
        $smscode->add($data);

        return $outputArr;
    }

// 验证验证码时间是否过期 10分钟
    public function _checkTime($sendTime, $overTime = 600)
    {
        if (time() - $sendTime > $overTime) {
            return false;
        } else {
            return true;
        }
    }

//进行一个关注切换
    public function toggle(){
        $openid = get_openid();
        if(!is_wechat_browser()) $this->error('只能在微信浏览器中执行该功能');
        $type =I('get.type');
        if($type == 'pin'){
            $model = M('BsPinche');
            $surl = create_mobile_url('detail',array('id'=>I('id')));
        }elseif($type == 'yu'){
            $model = M('BsPinche');
            $surl = create_mobile_url('yuDetail',array('id'=>I('id')));
        }else{
            $this->error('类型错误!');
        }
        
        $config = get_addon_settings();
        $attention = $config['attention'];
        if ($attention == 1) {
            $fans_info = get_fans_info($openid);
            if ($fans_info['is_subscribe'] != 1) {
                $url = create_addon_url('attention');
                $this->error('关注公众号才可以关注路线哦',$url);
            }
        }

        $mpid = get_mpid();
        $id = I('id',0,'intval');
        if(!$id || !$s = $model->where(array('mpid'=>$mpid,'id'=>$id))->find())  $this->error('找不到该订单');

        $where = array('mpid'=>$mpid,'openid'=>$openid,'did'=>$id);
        $data = M('BsGuanzhu')->where($where)->find();
        $config = get_addon_settings();
        /*编辑模板信息内容*/
        $temp_id = "ddWEFy_sXCKIuOra4Lf9vvMq31bKYe0EkmaAfp71xuY";
        $arr = array(
            "template_id"=>$temp_id,
            "url"=>$surl,
            "topcolor"=>"#FF0000",
            "data"=>array(
              'first'=>array(
                'value'=>'有用户关注了你的行程哦！',
                "color"=>"#173177"
              ),
              'keyword1'=>array(
                'value'=>get_fans_nickname($openid),
                "color"=>"#173177"
              ),
              'keyword2'=>array(
                'value'=>date('Y-m-d H:i:s',time()),
                "color"=>"#173177"
              ),
              'remark'=>array(
                'value'=>'点击详情并及时处理',
                "color"=>"#173177"
              ),
            )
        );
        // $arr = array(
        //     "template_id"=>$temp_id,
        //     "url"=>$url,
        //     "topcolor"=>"#FF0000",
        //     "data"=>array(
        //       'info'=>array(
        //         'value'=>'有人关注了你的行程',
        //         "color"=>"#173177"
        //       ),
        //       'date'=>array(
        //         'value'=>date('Y-m-d H:i:s',time()),
        //         "color"=>"#173177"
        //       ),
        //     )
        // );
        /*编辑模板信息内容*/
        if(!$data){
            $add['mpid'] = $mpid;
            $add['openid'] = $openid;
            $add['did'] = $id;
            $add['type'] = $type;
            $add['create_time'] = time();
            if(M('BsGuanzhu')->add($add)){
                $this->sendTemp($s['openid'],$arr); 
                $this->success('关注成功!');            //初次关注
            }
        }else{
            if($data['status']){
               if(M('BsGuanzhu')->where($where)->setField('status',0)){
                $this->success('取消成功');            //取消关注
                }else{
                    echo M('BsGuanzhu')->getError();
                }
            }else{
                if(M('BsGuanzhu')->where($where)->setField('status',1)){
                $this->sendTemp($s['openid'],$arr); 
                $this->success('关注成功');            //重复关注
                } 
            }
        }
        
}

//在线订座新增
    public function yuAdd(){
        $config = get_addon_settings();
        $openid = get_openid();
        $mpid = get_mpid();
        $userinfo = get_fans_info();
        /*是否有置顶收费*/
        for ($i=1; $i <= 3; $i++) {
            $key = 'charge'.$i;
            if(!empty($config[$key])){
                $charge[] = explode('#', $config[$key]);
            }
        }

        if(IS_POST){
            $_POST['type'] = 2;
            $_POST['gotime'] = strtotime($_POST['gotime']);
            $model = D('Addons://pinche/BsYu');
            if($data = $model->create()){
                //发送次数是否已经超标
                $user_add_num = (int)$config['user_add_num'];
                if ($user_add_num) {
                    // 查询 用户今日发布了多少条
                    $now_date = strtotime(date("y-m-d", strtotime('now')));
                    $user_pinche_count = M('BsPinche')->where(array('openid'=>$openid,'mpid'=>$mpid,'types'=>1,'pubtime'=>array('gt',$now_date)))->count();
                    if ($user_pinche_count >= $user_add_num) {
                        $this->error('您今日发布超过最大限制 ' . $user_add_num . '条/天');
                        exit();
                    }
                }
                /*扣除金额*/
                $total_num = 0;
                $charge_num = (int)$config['charge'];
                if($charge_num) $total_num +=  $charge_num;     //发布是否需要收费
                if($data['is_top']){                            //是否有置顶收费
                    $config_key = 'charge'.$data['is_top'];
                    $charge_top = $config["$config_key"];
                    $charge_top_arr = explode('#', $charge_top);
                    $charge_time = $charge_top_arr[0];
                    $charge_money = $charge_top_arr[1];
                    $total_num+=$charge_money;
                }            
                //查看用户是否有钱支付
                if($total_num){
                    if($userinfo['money']/100 < $total_num){
                        $this->error('用户余额不足，请先充值',create_mobile_url('recharge'));
                        exit();
                    }
                    M('mp_fans')->startTrans();
                    M('mp_fans')->where(array('openid'=>$openid,'mpid'=>$mpid))->setDec('money', $total_num * 100);//置顶天数
                    $data['top_time'] = time() + ($charge_time * 24 * 60 * 60);
                }

                if($model->add($data)){
                    M('mp_fans')->commit();
                    /*设置session值*/
                    session('tel',I('post.tel'));
                    $this->success('发布成功!',create_mobile_url('yuList'));
                }else{
                    M('mp_fans')->rollback();
                    $this->error('发布失败，请重新发布');
                }

            }else{
                $this->error($model->getError());
            }
        }else{
            // 如果后台设置 发布必须关注本公众号
            if ($config['attention'] == 1) {
                $fans_info = get_fans_info($openid);
                if ($fans_info['is_subscribe'] != 1) {
                    $url = create_mobile_url('attention');
                    header("location: {$url}");
                }
            }
            // 查询是否验证手机号
            if (!$this->check_user_is_vail()) {
                redirect(create_addon_url('check_phone'));
            }else{
                // $value['tel'] =  D('bs_pinche_mobile_check')->where(array('mpid'=>$mpid,'openid'=>$openid,'status'=>1))->getField('mobile');
                $value['tel'] = session('tel');
            }
            //是否需要通过车主验证
            if($config['car_is_cert_addinform'] == 1){
                $data = D('bs_pinche_car_cert')->where(array('mpid'=>$mpid,'openid'=>$openid,'status'=>1))->find();
               if(!$data){
                    redirect(create_mobile_url('car_cert'));
               }else{
                 $value['chexing'] = $data['car_type'];
                 $value['user']    = $data['nickname'];
               }
            }
            $this->assign('chargeNum',$config['charge']);    //设置收费金额
            $this->assign('value',$value);
            $this->assign('charge',$charge);
            $this->display();
        }
       
    }

//在线订座列表
    public function yuList(){
        $stype = I('stype');
        if($stype && $stype == 'gotime'){
            $this->assign('go','sel');
        }else{
            $this->assign('pub','sel');
        }
        $config = get_addon_settings();
        // dump($config);
        for ($i=1; $i <= 3; $i++) { 
        $key = 'ad'.$i;
        $key2 = 'ad'.$i.'url';
        if(!empty($config[$key])){
            $arr[$i]['img'] = $config[$key];
            $arr[$i]['url'] = $config[$key2];
            }
        }
        $jssdk_sign = get_jssdk_sign_package();
        $this->assign('jsinfo', $jssdk_sign);

        $this->assign('config',$config);
        $this->assign('arr',$arr);   //这里是轮播图片
        $this->display();

    }

    /*
     * ajax 列表
     */
    public function yuLists()
    {
        $page  = I('get.page');     //页数
        $pagesize = I('get.pageSize');
        $stype = I('get.stype','pubtime');    //排序方法
        $from  = I('get.ffrom');    //出发地
        $to    = I('get.tto');      //目的地
        $config= get_addon_settings();  //获取配置
        $where = 'types = 1 ';
        $order = "is_top DESC , top_time DESC";
        //过期不显示
        if($config['timeout']==2){
            $where .= "gotime > ".time();
        }
        if($from){
             $where .= $where  ? ' and ': '';
            $where .= "( `from` like '%".$from."%' OR  `through` like '%" . $from . "%' )"; 
        }
        if($to){
             $where .= $where  ? ' and ': '';
            $where .= "( `to` like '%".$to."%' OR  `through` like '%" . $to . "%' )"; 
        }
        if($stype){
            $order .= ','.$stype." DESC";
        }
        $model = D('Addons://pinche/BsYu');
        $data['status'] = true;
        $data['data']   =  $model->getLists($where,$page,$pagesize,$order);
       
        $this->ajaxReturn($data);
    }

    /*获取当前订单数据*/
    public function getOne(){
        $mpid = get_mpid();
        $id = I('get.id',0,'intval');
        if(!$id || ! $data = D('Addons://pinche/BsYu')->getOne(array('a.mpid'=>$mpid,'a.id'=>$id))){
            $this->error('找不到该订单');
        }
        return $data;
    }

    public function yuDel(){
        $data = $this->getOne();
        $config = get_addon_settings();
        if(!$data['status'])  $this->error('该订单已经过期');
        $id = I('get.id');
        M('BsPinche')->startTrans();    //进行事务的跳转
        if(M('BsPinche')->where(array('id'=>$id,'mpid'=>get_mpid(),'types'=>1))->setField('status',0)){
            /*修改乘客状态并发送信息提醒用户*/
            $users = M('BsYus')->where(array('did'=>$id,'status'=>1,'mpid'=>get_mpid()))->getField('openid',true);
            if(M('BsPinche')->where(array('id'=>$id,'types'=>1))->setDec('yu_count',M('BsYus')->where(array('did'=>$id,'status'=>1,'mpid'=>get_mpid()))->sum('people_count'))){
                 if(M('BsYus')->where(array('openid'=>array('in',$users),'did'=>$id))->setField('status',2)){
                $temp_id = "P0pQbpGpc2BJk5L4nl2aZDey9AovJN5w9MkGOITCwUM";
                $url = create_mobile_url('myYu');
                $arr = array(
                    "template_id"=>$temp_id,
                    "url"=>$url,
                    "topcolor"=>"#FF0000",
                    "data"=>array(
                      'first'=>array(
                        'value'=>'你的货物已经到达目的地，请留意',
                        "color"=>"#173177"
                      ),
                      'keyword1'=>array(
                        'value'=>date('Y-m-d H:i',time()),
                        "color"=>"#173177"
                      ),
                      'keyword2'=>array(
                        'value'=>'货找车',
                        "color"=>"#173177"
                      ),
                      'keyword3'=>array(
                        'value'=>'已结束',
                        "color"=>"#173177"
                      ),
                      'keyword4'=>array(
                        'value'=>$config['title'],
                        "color"=>"#173177"
                      ),
                      'keyword5'=>array(
                        'value'=>"你的货物已到达",
                        "color"=>"#173177"
                      ),
                      'remark'=>array(
                        'value'=>"如有疑问请致电客服",
                      ),
                    )
                );
                $this->sendTemp($users,$arr);
                M('BsPinche')->commit();    //进行事务的跳转
                $this->success('已结束',create_mobile_url('yuList'));
            }
            }
           
            
        }
         M('BsPinche')->rollback();
         $this->error('请重新尝试');
    }
    /*订单详情*/
    public function yuDetail(){
        $data = $this->getOne();
        $this->assign('data',$data);
        $jssdk_sign = get_jssdk_sign_package();
        $this->assign('jsinfo', $jssdk_sign);
        $config = get_addon_settings();
        $this->assign('config',$config);
        $this->display();
    }

    /*我要预订*/
    public function yuDing(){
       $data = $this->getOne(); //获取订单信息
       $config = get_addon_settings();
       // if(!$data['status'])  $this->error('该订单已经过期');       //过期订单无法预订座位
       $size = $data['num']-$data['yu_count'];
       if(IS_POST){
         if(!is_wechat_browser()) $this->error('只能在微信浏览器中执行该功能');
         $_POST['gotime'] = strtotime($_POST['gotime']);
         $_POST['did']    = I('get.id');
         $model = D('Addons://pinche/BsYus');
         if(get_openid() == $data['openid']) $this->error('不能预订自己发布的订单哦!');
         if($size < 1)   $this->error('当前行程已经满人');
         if(I('post.people_count') > $size) $this->error('预定座位不能超过现有的座位');   //预订座位不能超过当前剩余座位
            
         if($model->create()){
            //判断下是否已经过期
            // $now = time();
            // if(strtotime($data['gotime']) < $now || $data['status'] == 0){
            //     $this->error('当前行程已经过期');
            //     exit();
            // }   
            //当前订单是否已经满人
            if($id = $model->add()){
                //发送模板消息给司机
                $temp_id = "P0pQbpGpc2BJk5L4nl2aZDey9AovJN5w9MkGOITCwUM";
                $url = create_mobile_url('yuSi',array('id'=>$id));
                $arr = array(
                    "template_id"=>$temp_id,
                    "url"=>$url,
                    "topcolor"=>"#FF0000",
                    "data"=>array(
                      'first'=>array(
                        'value'=>'有人预定了你的车辆，请尽快确认',
                        "color"=>"#173177"
                      ),
                      'keyword1'=>array(
                            'value'=>date('Y-m-d H:i',time()),
                            "color"=>"#173177"
                        ),
                      'keyword2'=>array(
                        'value'=>'货找车',
                        "color"=>"#173177"
                      ),
                      'keyword3'=>array(
                        'value'=>'待确定',
                        "color"=>"#173177"
                      ),
                      'keyword4'=>array(
                        'value'=>$config['title'],
                        "color"=>"#173177"
                      ),
                      'keyword5'=>array(
                        'value'=>"货主预订了你的从".$data['from'].'到'.$data['to']."的订单",
                        "color"=>"#173177"
                      ),
                      'remark'=>array(
                        'value'=>"如有疑问请致电客服",
                        "color"=>"#173177"
                      ),
                    )
                );
                $this->sendTemp($data['openid'],$arr);
                /*设置session*/
                  session('contact',I('post.contact'));
                  session('tel',I('post.tel'));
                /*设置session*/
                $this->success('预订成功，请等待司机回复!',create_mobile_url('yuDetail',array('id'=>I('get.id'))));
            }else{
                $this->error('预订失败，请重新预订');
            }
         }else{
            $this->error($model->getError());
         }
       }else{
        /*获取默认值*/
          $val['contact'] = session('contact');
          $val['tel'] = session('tel');
          $val['to']  = $data['to'];
          $this->assign('val',$val);
        /*获取默认值*/
        $this->assign('money',$data['money']);
        /*获取当前座位数*/
        $this->assign('size',$size);
        $this->display();
       }
    }

    /*检查订单是否有误*/
    public function checkYu(){
        $id = I('get.id',0,'intval');
        $mpid = get_mpid();
        $data=D('Addons://pinche/BsYus')->getInfo(array('a.id'=>$id,'a.mpid'=>$mpid));
        if(!$id || !$data['id']){
            $this->error('找不到该订单');
        }
        return $data;
    }

    /*司机预订页*/
    public function yuSi(){
        $data = $this->checkYu();
        $this->assign('data',$data);
        $this->display();
    }

   /*接单*/
   public function yuJie(){
       $data = $this->checkYu();
       $openid = get_openid();
       $mpid = get_mpid();
       $config = get_addon_settings();
       if($data['dopenid'] != $openid) $this->error('只允许司机进行当前操作');
       if($data['bcount'] - $data['byucount'] < $data['people_count'] ) $this->error('已没有足够的座位');
       if($data['status'] ==1) $this->error('该订单已接受');
       $model = M('BsYus');
       $model->startTrans();    //进行事务的跳转
       if($model->where(array('id'=>I('get.id')))->setField('status',1)){
            if(M('BsPinche')->where(array('id'=>$data['did']))->setInc('yu_count',$data['people_count'])){
                $model->commit();
                /*成功发送模板消息通知用户*/
                $temp_id = "P0pQbpGpc2BJk5L4nl2aZDey9AovJN5w9MkGOITCwUM";
                $url = create_mobile_url('yuDetail',array('id'=>$data['did']));
                $arr = array(
                    "template_id"=>$temp_id,
                    "url"=>$url,
                    "topcolor"=>"#FF0000",
                    "data"=>array(
                      'first'=>array(
                        'value'=>'司机已经接了你的订单，请留意装车时间',
                        "color"=>"#173177"
                      ),
                      'keyword1'=>array(
                            'value'=>date('Y-m-d H:i',time()),
                            "color"=>"#173177"
                          ),
                      'keyword2'=>array(
                        'value'=>'货找车',
                        "color"=>"#173177"
                      ),
                      'keyword3'=>array(
                        'value'=>'已确定',
                        "color"=>"#173177"
                      ),
                      'keyword4'=>array(
                        'value'=>$config['title'],
                        "color"=>"#173177"
                      ),
                      'keyword5'=>array(
                        'value'=>"司机已经接了你的订单",
                        "color"=>"#173177"
                      ),
                      'remark'=>array(
                        'value'=>"如有疑问请致电客服",
                      ),
                    )
                );
                M('BsPinche')->where(array('id'=>$data['did']))->setField('status',1);
                $this->sendTemp($data['openid'],$arr);
                $this->success('接单成功',create_mobile_url('user'));
            }else{
                $model->rollback();
                $this->error(M('BsPinche')->getError());
            }
       }else{
            $this->error('接单失败2');
       }
   }

   /*拒绝订单
    *   type = si    司机拒绝用户
    *   type = customer  用户拒绝司机
   */
   public function yuJu(){
        $data   = $this->checkYu();
        $openid = get_openid();
        $config = get_addon_settings();
        $type   = I('get.type','si');
        $model = M('BsYus');
        if($data['status'] == -1) $this->error('当前订单已经过期',create_mobile_url('yuDetail',array('id'=>$data['did'])));

        if($data['status'] == 1){
        	if( !M('BsPinche')->where(array('id'=>$data['did'],'types'=>1))->setDec('yu_count',$data['people_count']))   $this->error('错误，请重新操作！');
        }
         if($type == 'si'){
            if($data['dopenid'] != $openid) $this->error('只允许司机进行当前操作');
             //司机拒绝用户
            $user = $data['openid'];
            $first = "司机取消了你的订单";
            $info = '司机取消了你的订单，原因：'.I('post.text');
        }else{
            $first = "货主取消了你的订单";
            $info = '用货主取消了你的车辆';
            //用户拒绝司机
            $user = $data['dopenid'];
        }
        if($model->where(array('id'=>I('get.id')))->setField('status',-1)){
            //发送模板文件通知
            $url = create_mobile_url('yuDetail',array('id'=>$data['did']));
            $temp_id = "P0pQbpGpc2BJk5L4nl2aZDey9AovJN5w9MkGOITCwUM";
                $arr = array(
                    "template_id"=>$temp_id,
                    "url"=>$url,
                    "topcolor"=>"#FF0000",
                    "data"=>array(
                      'first'=>array(
                        'value'=>$first,
                        "color"=>"#173177"
                      ),
                      'keyword1'=>array(
                        'value'=>date('Y-m-d H:i',time()),
                        "color"=>"#173177"
                      ),
                      'keyword2'=>array(
                        'value'=>'货找车',
                        "color"=>"#173177"
                      ),
                      'keyword3'=>array(
                        'value'=>'已取消',
                        "color"=>"#173177"
                      ),
                      'keyword4'=>array(
                        'value'=>$config['title'],
                        "color"=>"#173177"
                      ),
                      'keyword5'=>array(
                        'value'=>$info,
                        "color"=>"#173177"
                      ),
                      'remark'=>array(
                        'value'=>"如有疑问请致电客服",
                      ),
                    )
                );
            $this->sendTemp($user,$arr);                 //群发模板
            $this->success('拒绝成功',create_mobile_url('user'));
        }else{
            $this->error('拒绝失败');
        }
   }

   /*司机路线管理*/
   public function routeManage(){
       //获取所有的行程
       $openid = get_openid();
       $mpid   = get_mpid();

       $data = D('Addons://pinche/BsYu')->getRouteDatas(array('openid'=>$openid,'mpid'=>$mpid));
       $this->assign('data',$data);
       $this->display();
   }

   /*路线编辑*/
   public function routeEdit(){
        $data = $this->getOne();
        $config = get_addon_settings();
        for ($i=1; $i <= 3; $i++) {
            $key = 'charge'.$i;
            if(!empty($config[$key])){
                $charge[] = explode('#', $config[$key]);
            }
        }
        if(IS_POST){
            $_POST['gotime'] = strtotime($_POST['gotime']);
            $model = D('Addons://pinche/BsYu');
            if($s = $model->create()){
                /*座位不得少于预定了的座位数*/
                if($s['num'] < $data['yu_count']) $this->error('座位数不得少于已预订人数');
                /*扣除金额*/
                $total_num = 0;
                if($s['is_top'] > $data['is_top']){                            //是否有置顶收费
                    $config_key = 'charge'.$s['is_top'];
                    $charge_top = $config["$config_key"];
                    $charge_top_arr = explode('#', $charge_top);
                    $charge_time = $charge_top_arr[0];
                    $charge_money = $charge_top_arr[1];
                    $total_num+=$charge_money;
                }            
                //查看用户是否有钱支付
                if($total_num){
                    if($userinfo['money']/100 < $total_num){
                        $this->error('用户余额不足，请先充值',create_mobile_url('recharge'));
                        exit();
                    }
                    M('mp_fans')->startTrans();    //进行事务的跳转
                    M('mp_fans')->where(array('openid'=>$openid,'mpid'=>$mpid))->setDec('money', $total_num * 100);//置顶天数
                    $s['top_time'] = time() + ($charge_time * 24 * 60 * 60);
                }

                if($model->where(array('id'=>I('get.id')))->save($s)){
                    M('mp_fans')->commit();
                    /*获取所有关注用户以及所有的乘客*/
                    $userData = M('BsGuanzhu')->where(array('mpid'=>get_mpid(),'did'=>I('get.id'),'type'=>'yu','status'=>1))->getField('openid',true);
                    $temp_id = "P0pQbpGpc2BJk5L4nl2aZDey9AovJN5w9MkGOITCwUM";
                    $url = create_mobile_url('yuDetail',array('id'=>I('get.id')));
                    $arr = array(
                        "template_id"=>$temp_id,
                        "url"=>$url,
                        "topcolor"=>"#FF0000",
                        "data"=>array(
                          'first'=>array(
                            'value'=>'你关注的司机修改了他的行程，请注意查看',
                            "color"=>"#173177"
                          ),
                          'keyword1'=>array(
                            'value'=>date('Y-m-d H:i',time()),
                            "color"=>"#173177"
                          ),
                          'keyword2'=>array(
                            'value'=>'货找车',
                            "color"=>"#173177"
                          ),
                          'keyword3'=>array(
                            'value'=>'已关注',
                            "color"=>"#173177"
                          ),
                          'keyword4'=>array(
                            'value'=>$config['title'],
                            "color"=>"#173177"
                          ),
                          'keyword5'=>array(
                            'value'=>"你关注的从".I('post.from').'到'.I('post.to').'的路程有所修改，请查看',
                            "color"=>"#173177"
                          ),
                          'remark'=>array(
                            'value'=>"如有疑问请致电客服",
                          ),
                        )
                    );
                    $this->sendTemp($userData,$arr);
                    $this->success('编辑成功!',create_mobile_url('yuList'));
                }else{
                    M('mp_fans')->rollback();
                    $this->error('编辑失败，请重新提交');
                }
            }else{
                $this->error($model->getError());
            }
        }else{
            $this->assign('charge',$charge);
            // dump($data);
            $this->assign('data',$data);
            $this->display();
        }
   }

   /*查看所有乘客*/
   public function customer(){
     $data   = $this->getOne();
     $openid = get_openid();
     $mpid   = get_mpid();
     $id     = I('get.id',0,'intval');
     $data = D('Addons://pinche/BsYus')->getMyCustomer($id); //获取路线乘客
     $this->assign('data',$data);
     $this->display();
   }

   /*我的订单*/
   public function myYu(){
       $openid = get_openid();
       $data = D('Addons://pinche/BsYus')->getMyYu($openid); //获取路线乘客
       $this->assign('data',$data);
       $this->display();
   }

   /*我的关注*/
   public function myGuan(){
      $openid = get_openid();
      $mpid   = get_mpid();
      $type = I('type','yu');
      $this->assign('type',$type);
      /*获取所有的关注车程列表*/
      if($type == 'pin'){
         $info = M('BsPinche')->field('a.*,c.nickname,c.headimgurl,c.sex')->alias('a')->join('__BS_GUANZHU__ as b on a.id = b.did')->join('__MP_FANS__ as c on a.openid = c.openid ')->where(array('b.mpid'=>$mpid,'a.types'=>2,'b.openid'=>$openid,'b.status'=>1,'type'=>$type))->select();
     }else{
         $info = M('BsPinche')->field('a.*,c.nickname,c.headimgurl,c.sex')->alias('a')->join('__BS_GUANZHU__ as b on a.id = b.did')->join('__MP_FANS__ as c on a.openid = c.openid ')->where(array('b.mpid'=>$mpid,'b.openid'=>$openid,'b.status'=>1,'type'=>$type,'a.types'=>1))->select();
     }
     
      $this->assign('data',$info);
      $this->display();
   }

   //模板发送接口
   public function sendTemp($userData,$arr){
    //发布消息通知用户
       $wechatObj = get_wechat_obj();
       if(is_array($userData)){
            foreach ($userData as $value) {
               $arr["touser"] = $value;
               $res =  $wechatObj->sendTemplateMessage($arr);
           }
       }else{
               $arr["touser"] = $userData;
               $res =  $wechatObj->sendTemplateMessage($arr);
       }
   }


}
